// components/cart-item/index.js
import {CartModel} from '../../model/cart'
import { config } from '../../config'
import {Tools} from '../../utils/tools'
var cart = new CartModel()
var tools = new Tools()
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    model: Object
  },

  /**
   * 组件的初始数据
   */
  data: {
    count:1
  },

  /**
   * 组件的方法列表
   */
  methods: {
    setCount:function(e){
      var count = e.currentTarget.dataset.count
      var data = this.properties.model
      if (!e.currentTarget.dataset.bool) {
        cart.delete(data.goodsId,data.cartId).then(
          res=>{
            if (res.code === 0) {
              this.triggerEvent("upData")
            }
          }
        )
      }else{
        cart.save(data.goodsId,data.goodsSkuId).then(
          res=>{
            if (res.code === 0) {
              this.triggerEvent("upData")
            }
          }
        )
        count += 1
      }
      this.setData({
        count: count
      })
    },

    cartList(){
      
      if (tools.isCartList(this.properties.model.id)) {
        for (let i = 0; i < config.cartList.length; i++) {
          if (this.properties.model.id === config.cartList[i]) {
            config.cartList.splice(i,1);
            break
          }
        }
      } else {
        config.cartList.push(this.properties.model.id)
      }
      this.triggerEvent("setCart")
    },
  }
})
